﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace XMLFormat
{
    class XMLChange
    {
        /// <summary>
        /// v0.1格式转成v0.2格式
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool V01ToV02(string fileName)
        {
            FileInfo file = new FileInfo(fileName);
            string ex = file.Extension.ToLower();
            if (ex == ".xml")
            {
                XDocument xd = XDocument.Load(fileName);
                XElement root = xd.Element("root");
                if (root == null || root.Attribute("version") == null || root.Attribute("version").Value!="0.1")
                {
                    return false;
                }
                else
                {
                    root.SetAttributeValue("version","0.2");
                    foreach (var product in root.Elements("product"))
                    {
                        XElement prices = new XElement("prices");
                        var priceList = product.Elements("price");
                        prices.Add(priceList);
                        product.Add(prices);
                        priceList.Remove();
                    }
                    xd.Save(file.FullName + "copy" + file.Extension);
                    return true;
                }
            }
            else
            {
                return false;
            }
            
        }

        internal static bool Remove0price(string fileName)
        {
            FileInfo file = new FileInfo(fileName);
            string ex = file.Extension.ToLower();
            if (ex == ".xml")
            {
                XDocument xd = XDocument.Load(fileName);
                XElement root = xd.Element("root");
                if (root == null || root.Attribute("version") == null || root.Attribute("version").Value != "0.2")
                {
                    return false;
                }
                else
                {
                    foreach (var product in root.Elements("product"))
                    {
                        var i = (from el in product.Element("prices").Elements("price") where el.Value == "0" select el).FirstOrDefault();
                        if (i!=null)
                        {
                            i.Remove();
                        }
                    }
                    xd.Save(file.FullName);
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
    }
}
